<template>
  <el-dialog v-model="dialogVisible" width="540" title="申请注册" destroy-on-close :show-close="false"
    :close-on-click-modal="false" custom-class="login-form-dialog">
    <div class="dialog-body">
      <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="rules" label-position="top"
        label-width="120px">
        <el-form-item prop="cargoOwnerName">
          <el-input v-model="formData.cargoOwnerName" :maxlength="100" placeholder="请输入企业名称"
            @blur="validCargoOwnerName">
            <template #prefix>
              <img src="@/assets/imgs/enterprise-icon.png" />
            </template>
            <template #suffix>
              <img v-if="isShowNameIcon" :src="isRegisterNameIcon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="contactPerson">
          <el-input v-model="formData.contactPerson" :maxlength="20" placeholder="请输入姓名">
            <template #prefix>
              <img src="@/assets/imgs/profile-icon.png" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="username">
          <el-input v-model="formData.username" :maxlength="20" placeholder="请输入账号" @blur="validAccount">
            <template #prefix>
              <img src="@/assets/imgs/profile-icon.png" />
            </template>
            <template #suffix>
              <img v-if="isShowAccountIcon" :src="isRegisterAccountIcon" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="formData.password" type="password" :show-password="true" :maxlength="16"
            placeholder="请输入密码">
            <template #prefix>
              <img src="@/assets/imgs/password-icon.png" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="mobile">
          <el-input v-model="formData.mobile" :maxlength="11" placeholder="请输入手机号">
            <template #prefix>
              <img src="@/assets/imgs/user-icon.png" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <slide-verify ref="slideVerifyRef" @success="onVerifySuccess" />
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input v-model="formData.verifyCode" :maxlength="6" placeholder="请输入验证码">
            <template #prefix>
              <img src="@/assets/imgs/verify-icon.png" />
            </template>
            <template #suffix>
              <el-button v-show="validMess==='获取验证码'" :disabled="isVerifySuccess" type="primary" link
                @click="getSmsCode()" class="code-text">{{validMess}}</el-button>
              <el-button v-show="validMess!=='获取验证码'" class="code-text count-btn" type="primary"
                link>{{validMess}}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formData.remark" :maxlength="100" placeholder="请输入备注信息">
            <template #prefix>
              <img src="@/assets/imgs/info-icon.png" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="footer">
        <el-button @click="dialogVisible=false"> 取消 </el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import * as LoginApi from '@/api/login'
  import { cloneDeep } from 'lodash'

  const emit = defineEmits(['success'])
  const message = useMessage()
  const validMess = ref('获取验证码')
  const formLoading = ref(false)
  const dialogVisible = ref(false)
  const isVerifySuccess = ref(true)
  const isShowNameIcon = ref(false)
  const isRegisterName = ref(false)
  const isRegisterAccount = ref(false)
  const isShowAccountIcon = ref(false)
  const formRef = ref()
  const slideVerifyRef = ref()
  const formData = ref({
    cargoOwnerName: undefined,
    contactPerson: undefined,
    username: undefined,
    password: undefined,
    mobile: undefined,
    verifyCode: undefined,
    remark: undefined
  })
  let countNum = ref(59)
  let intervalId = null


  const isRegisterNameIcon = computed(() => {
    if (isRegisterName.value) {
      return new URL('@/assets/imgs/yes-icon.png', import.meta.url).href
    }
    return new URL('@/assets/imgs/error-icon.png', import.meta.url).href
  })

  const isRegisterAccountIcon = computed(() => {
    if (isRegisterAccount.value) {
      return new URL('@/assets/imgs/yes-icon.png', import.meta.url).href
    }
    return new URL('@/assets/imgs/error-icon.png', import.meta.url).href
  })

  const countNumFun = () => {
    if (countNum.value <= 0) {
      clearInterval(intervalId)
      countNum.value = 59
      validMess.value = '获取验证码'
      return
    }
    countNum.value -= 1
    validMess.value = countNum.value + 's'
  }

  const validateUsername = (rule, value, callback) => {
    if (/^.*\D.*$/.test(value)) {
      return callback()
    } else {
      return callback(new Error('账号不能为纯数字'))
    }
  }

  const validateString = (rule, value, callback) => {
    if (
      /^((?=.*[A-Za-z])(?=.*\d)|(?=.*[A-Za-z])(?=.*[!@#$%^&*()_+\-\=])|(?=.*\d)(?=.*[!@#$%^&*()_+\-\=]))[A-Za-z\d!@#$%^&*()_+\-\=]{6,16}$/.test(
        value
      )
    ) {
      return callback()
    } else {
      return callback(new Error('密码长度6-16位，必须包含数字、字母、特殊符号两种以上'))
    }
  }

  const validateMobile = (rule, value, callback) => {
    if (/^1[3-9]\d{9}$/.test(value)) {
      return callback()
    } else {
      return callback(new Error('请输入正确手机号'))
    }
  }

  const rules = reactive({
    cargoOwnerName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
    contactPerson: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      { validator: validateUsername, trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 16, message: '密码长度6-16位', trigger: 'blur' },
      { validator: validateString, trigger: 'blur' }
    ],
    mobile: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validateMobile, trigger: 'blur' }
    ],
    verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  })

  const open = async () => {
    dialogVisible.value = true
    resetFn()
  }

  const validCargoOwnerName = async () => {
    if (!formData.value.cargoOwnerName) {
      isShowNameIcon.value = false
      return
    }
    isShowNameIcon.value = true
    try {
      formLoading.value = true
      await LoginApi.validCargoOwnerApprovalName({ cargoOwnerName: formData.value.cargoOwnerName?.trim() })
      isRegisterName.value = true
    } catch {
      isRegisterName.value = false
    } finally {
      formLoading.value = false
    }
  }

  const validAccount = async () => {
    if (!formData.value.username) {
      isShowAccountIcon.value = false
      return
    }
    isShowAccountIcon.value = true
    try {
      formLoading.value = true
      await LoginApi.validUsername({ username: formData.value.username?.trim() })
      isRegisterAccount.value = true
    } catch {
      isRegisterAccount.value = false
    } finally {
      formLoading.value = false
    }
  }

  const onVerifySuccess = (value) => {
    isVerifySuccess.value = value
  }

  const getSmsCode = async () => {
    if (!formData.value.mobile) {
      message.warning('请输入正确手机号')
      return
    }
    try {
      formLoading.value = true
      isVerifySuccess.value = true
      slideVerifyRef.value?.initSlider()
      const res = await LoginApi.sendSmsCode({
        mobile: formData.value.mobile,
        scene: 19
      })
      message.success('验证码发送成功')
      validMess.value = countNum.value + 's'
      intervalId = setInterval(() => {
        countNumFun()
      }, 1000)
    } finally {
      formLoading.value = false
    }
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    try {
      formLoading.value = true
      const data = cloneDeep(formData.value)
      data.cargoOwnerName = data.cargoOwnerName?.trim()
      data.username = data.username?.trim()
      await LoginApi.register(data)
      message.success('提交成功，等待审批')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }

  const resetFn = () => {
    formData.value = {
      cargoOwnerName: undefined,
      contactPerson: undefined,
      username: undefined,
      password: undefined,
      mobile: undefined,
      verifyCode: undefined,
      remark: undefined
    }
    countNum.value = 59
    clearInterval(intervalId)
    validMess.value = '获取验证码'
    isVerifySuccess.value = true
    isShowNameIcon.value = false
    isRegisterName.value = false
    isRegisterAccount.value = false
    isShowAccountIcon.value = false
    formRef.value?.resetFields()
  }

  defineExpose({ open })
</script>

<style lang="scss" scoped>
  .code-text.el-button {
    font-size: 16px;
  }

  .count-btn.el-button {
    color: #409EFE !important;
  }

  :deep(.el-input--default) {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
  }

  :deep(.el-button--large) {
    font-size: 16px;
  }

  :deep(.el-input__password) {
    font-size: 18px;
  }
</style>

<style lang="scss">
  .el-dialog.login-form-dialog {
    background: linear-gradient(181deg, #cae4ff 0%, #ffffff 24%);
    box-shadow: 0px 12px 48px 0px rgba(0, 0, 0, 0.03), 0px 9px 28px 0px rgba(0, 0, 0, 0.05), 0px 6px 16px 0px rgba(0, 0, 0, 0.08);
  }

  .login-form-dialog .el-dialog__header {
    padding: 30px 40px;
  }

  .login-form-dialog .el-dialog__title {
    font-weight: 500;
    font-size: 28px;
    font-family: PingFang SC, PingFang SC-500;
  }

  .login-form-dialog .el-dialog__body {
    padding: 0px 40px !important;
  }

  .login-form-dialog .el-dialog__footer {
    padding: 10px 20px;
    margin-top: 32px !important;
    border-top: 1px solid #E4E7ED;
  }
</style>